package com.example.demo.common;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.example.demo.common.Constant.USER_SESSION_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-26
 * Time: 21:42
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session!=null && session.getAttribute(USER_SESSION_KEY)!=null) {
             return  true;
        }
        response.setStatus(401);//返回401状态码-->提示用户->没有登陆权限
        return false;
    }
}
